﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

using Uber.Storage;
using Uber.HabboHotel.GameClients;
using Uber.HabboHotel.Users;
using Uber.HabboHotel.Users.Messenger;
using System.Data;

namespace Uber.HabboHotel.Misc
{
    class PixelManager
    {
        private const int RCV_EVERY_MINS = 15;
        private const int RCV_AMOUNT = 250;
        private const int BASE_AMOUNT = 200;

        public int currDay = 0;
        public DataTable items;
        public DataRow curritem;
        public Boolean KeepAlive;
        public LotteryManager lm;
        private Task WorkerThread;

        public PixelManager()
        {
            this.KeepAlive = true;

            this.WorkerThread = null;
            this.WorkerThread = new Task(Process, CancellationToken.None, TaskCreationOptions.LongRunning);

            this.lm = new LotteryManager();
        }

        public void Start()
        {
            this.WorkerThread.Start();
            currDay = 0;
            using (DatabaseClient dbClient = UberEnvironment.GetDatabase().GetClient())
            {
                curritem = dbClient.ReadDataRow("SELECT * FROM catalog_items WHERE page_id='16'");
                items = dbClient.ReadDataTable("SELECT * FROM `catalog_items` WHERE page_id='94' AND amount='1'");
            }
        }

        public void Stop()
        {
            this.KeepAlive = false;

            this.WorkerThread.Wait();
            this.WorkerThread.Dispose();
            this.WorkerThread = null;
        }

        private void Process()
        {
            while (KeepAlive)
            {
                if (WorkerThread != null /*|| (!WorkerThread.IsCanceled)*/)
                {
                    this.WorkerThread.Wait(RCV_EVERY_MINS * 1000);
                }

                if (UberEnvironment.GetGame().GetClientManager() != null)
                {
                    UberEnvironment.GetGame().GetClientManager().CheckPixelUpdates();
                }
            }
        }

        public Boolean NeedsUpdate(GameClient Client)
        {
            try { lm.Update(); }
            catch { UberEnvironment.GetLogging().WriteLine("Update Error"); }
            Double PassedMins = (UberEnvironment.GetUnixTimestamp() - Client.GetHabbo().LastActivityPointsUpdate) / 60;

            if (currDay != DateTime.Now.Day)
            {
                currDay = DateTime.Now.Day;
                int rand;
                bool not = true;
                do
                {
                    rand = (new Random()).Next(items.Rows.Count);
                    int itemid = Convert.ToInt32(items.Rows[rand]["item_ids"]);
                    if (itemid != Convert.ToInt32(curritem["item_ids"]))
                    {
                        not = false;
                    }
                } while (not);

                using (DatabaseClient dbClient = UberEnvironment.GetDatabase().GetClient())
                {
                    DataRow newItem = dbClient.ReadDataRow("SELECT * FROM furniture WHERE id='" + items.Rows[rand]["item_ids"] + "'");
                    dbClient.ExecuteQuery("UPDATE catalog_items SET catalog_name='" + newItem["item_name"] + "', item_ids=" + newItem["id"] + " WHERE page_id=16");
                }
            }

            if (PassedMins >= RCV_EVERY_MINS)
            {
                return true;
            }

            return false;
        }

        public void GivePixels(GameClient Client)
        {
            Double Timestamp = UberEnvironment.GetUnixTimestamp();
            int amount = this.GetPixelAmount(Client);

            Client.GetHabbo().LastActivityPointsUpdate = Timestamp;
            Client.GetHabbo().ActivityPoints += (Client.GetHabbo().IsUltraVip) ? amount * 2 : amount;
            Client.GetHabbo().UpdateActivityPointsBalance(true, amount);

            //if (Client.GetHabbo().Credits < 15000)
            {
                Client.GetHabbo().Credits = Client.GetHabbo().Credits + (10 + getNumFriends(Client));
                Client.GetHabbo().UpdateCreditsBalance(true);
            }
        }

        public int getNumFriends(GameClient gc)
        {
            try {
            List<string> FriendsNames = new List<string>();
            foreach (MessengerBuddy Buddy in gc.GetHabbo().GetMessenger().GetBuddies())
            {
                FriendsNames.Add(Buddy.Username);
            }
            return FriendsNames.Count;
            } catch (Exception e) {
                return 0;
            }
        }

        public int GetPixelAmount(GameClient gc)
        {
            try
            {
                List<string> FriendsNames = new List<string>();
                foreach (MessengerBuddy Buddy in gc.GetHabbo().GetMessenger().GetBuddies())
                {
                    FriendsNames.Add(Buddy.Username);
                }

                int friends = ((int)Math.Ceiling((double)FriendsNames.Count / 10));
                if (friends == 1) return 15;
                if (friends == 2) return 20;
                if (friends == 3) return 30;
                if (friends == 4) return 50;
                if (friends == 5) return 80;
                if (friends > 5) return 100;
                else return 0;
            }
            catch
            {
                UberEnvironment.GetLogging().WriteLine("Friends Error");
                return 0;
            }
        }
    }
}
